package com.itboye.textileexpres.main;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.itboye.textileexpes.beans.CollectionCateTypeModel;
import com.itboye.textileexpes.beans.ColletionFenyeBeans;
import com.itboye.textileexpes.presenter.ColloctionPresenter;
import com.itboye.textileexpres.R;
import com.itboye.textileexpres.base.BaseFragment;
import com.itboye.textileexpres.base.ResultEntity;
import com.itboye.textileexpres.base.SpPublicParams;
import com.itboye.textileexpres.collection.ActivityCollectionEdit;
import com.itboye.textileexpres.collection.ActivityCollectionSeaech;
import com.itboye.textileexpres.collection.CollectionGoodsListViewAdapter;
import com.itboye.textileexpres.collection.CollectionGridAdapter;
import com.itboye.textileexpres.login.LoginActivity;
import com.itboye.textileexpres.myset.ActivityCustomerService;
import com.itboye.textileexpres.top.GoodsDetailsActivity;
import com.itboye.textileexpres.util.IsMobileNumPhone;
import com.itboye.textileexpres.util.MyToast;
import com.itboye.textileexpres.util.SPUtils;
import com.itboye.textileexpres.widget.MyGridView;
import com.itboye.textileexpres.widget.XListView;
import com.itboye.textileexpres.widget.XListView.IXListViewListener;

public class CollectionFragment extends BaseFragment implements
		OnClickListener, Observer, IXListViewListener {
	ImageView back;
	TextView title;
	MyGridView type_grid;
	XListView goods_list;
	ImageView load_more_img;
	int Default_show = 2;
	int cloums = 4;
	boolean mIsShrink = true;
	TextView edit;
	CollectionGoodsListViewAdapter listViewAdapter;
	CollectionGridAdapter gridAdapter;
	EditText key_word;
	ColloctionPresenter colloctionPresenter;
	String uid;
	// ColletionFenyeBeans list;
	int pagesize = 1;
	ColletionFenyeBeans beans = new ColletionFenyeBeans();
	List<ColletionFenyeBeans.InfoBeans> list = new ArrayList<ColletionFenyeBeans.InfoBeans>();
	List<CollectionCateTypeModel> cateTypeModels = new ArrayList<CollectionCateTypeModel>();
	String type = "clean";
	ImageView img_search;
	ImageView img_other;
	RelativeLayout null_collect;
	ScrollView scroll_layout;
	TextView goods_num;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.fragment_collection;
	}

	@Override
	public void onMyActivityCreated() {
		// TODO Auto-generated method stub
		title.setText(R.string.collection);
		back.setVisibility(View.GONE);
		img_search.setVisibility(View.GONE);
		img_other.setVisibility(View.GONE);
		uid = (String) SPUtils.get(getActivity(), null, SpPublicParams.UID, "");
		IntentFilter filter = new IntentFilter("UpDateCollection");
		IntentFilter exitfilter = new IntentFilter("newshead");
		IntentFilter loginfilter = new IntentFilter("LoginSuccess");
		getActivity().registerReceiver(broadcastReceiver, filter);
		getActivity().registerReceiver(exitReceiver, exitfilter);
		getActivity().registerReceiver(broadcastReceiver, loginfilter);
		colloctionPresenter = new ColloctionPresenter(this);
		if ("".equals(uid) || uid == "") {
			NullCollect();
//			Intent intent = new Intent(getActivity(), LoginActivity.class);
//			startActivity(intent);
		} else {
			VisibleCollect();
			colloctionPresenter.FenYeQuery(uid, "10", pagesize + "", "", "");
			colloctionPresenter.CollectionCateType(uid);
			goods_list.setPullLoadEnable(true);
			goods_list.setPullRefreshEnable(true);
			goods_list.setXListViewListener(this);

			load_more_img.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (mIsShrink) {
						expand();
					} else {
						collapse();
					}
					setListViewHeightBasedOnChildren(type_grid);
				}
			});
			setListViewHeightBasedOnChildren(type_grid);
			goods_list.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(getActivity(),
							GoodsDetailsActivity.class);
					intent.putExtra("pid", list.get(arg2 - 1).getId());
					startActivity(intent);
				}
			});
		}

	}

	void NullCollect() {
		scroll_layout.setVisibility(View.GONE);
		goods_list.setVisibility(View.GONE);
		type_grid.setVisibility(View.GONE);
		null_collect.setVisibility(View.VISIBLE);
	}

	void VisibleCollect() {
		scroll_layout.setVisibility(View.VISIBLE);
		goods_list.setVisibility(View.VISIBLE);
		type_grid.setVisibility(View.VISIBLE);
		null_collect.setVisibility(View.GONE);
	}

	BroadcastReceiver exitReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			uid = (String) SPUtils.get(getActivity(), null, SpPublicParams.UID,
					"") + "";
			NullCollect();
		}
	};
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			uid = (String) SPUtils.get(getActivity(), null, SpPublicParams.UID,
					"") + "";
			toast("up");
			colloctionPresenter.FenYeQuery(uid, "10", pagesize + "", "", "");
			colloctionPresenter.CollectionCateType(uid);
		}
	};
	OnClickListener toTopClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			// if ((Integer) v.getTag() == 0) {
			// toast("此项已经置顶");
			// }
			// InfoBeans str = list.get((Integer) v.getTag());
			// for (int i = (Integer) v.getTag(); i > 0; i--) {
			//
			// InfoBeans s = list.get(i - 1);
			// list.remove(i);
			// list.add(i, s);
			// }
			// list.remove(0);
			// list.add(0, str);
			// toast("置顶");
			ColletionFenyeBeans model = new ColletionFenyeBeans();
			model.setUid(uid);
			model.setIds(list.get((Integer) v.getTag()).getId());
			colloctionPresenter.update(model);
			listViewAdapter.notifyDataSetChanged();
		}
	};

	// @Override
	// public void onResume() {
	// // TODO Auto-generated method stub
	// super.onResume();
	// colloctionPresenter = new ColloctionPresenter(this);
	// colloctionPresenter.FenYeQuery(uid, "10", pagesize + "", "", "");
	// colloctionPresenter.CollectionCateType(uid);
	// }

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = super.handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == ColloctionPresenter.ColloctFenye_success) {
				if (type.equals("load")) {

				} else {
					list.clear();
				}
				beans = (ColletionFenyeBeans) entity.getData();
				list.addAll(beans.getList());
				listViewAdapter = new CollectionGoodsListViewAdapter(
						getActivity(), list, toTopClickListener);
				goods_list.setAdapter(listViewAdapter);
				goods_num.setText(beans.getCount() + "");
				setListViewHeightBasedOnChildren(goods_list);
				if (list == null || list.size() == 0) {
					NullCollect();
				} else {
					VisibleCollect();
				}
				listViewAdapter.notifyDataSetChanged();
				stop();
			} else if (entity.getEventType() == ColloctionPresenter.ColloctFenye_fail) {
				// MyToast.toast("" + entity.getData());

			}
			if (entity.getEventType() == ColloctionPresenter.ColloctCate_success) {
				cateTypeModels.clear();
				cateTypeModels
						.addAll((Collection<? extends CollectionCateTypeModel>) entity
								.getData());
				if (cateTypeModels.size() > 8) {
					gridAdapter = new CollectionGridAdapter(getActivity(),
							cateTypeModels, 8);
				} else {
					gridAdapter = new CollectionGridAdapter(getActivity(),
							cateTypeModels, cateTypeModels.size());
				}
				type_grid.setAdapter(gridAdapter);
				// beans = (ColletionFenyeBeans) entity.getData();

			} else if ((entity.getEventType() == ColloctionPresenter.ColloctCate_fail)) {
				// MyToast.toast("" + entity.getData());
			}
			if (entity.getEventType() == ColloctionPresenter.ColloctTop_success) {
				MyToast.toast("" + entity.getData());
				colloctionPresenter
						.FenYeQuery(uid, "10", pagesize + "", "", "");
				listViewAdapter.notifyDataSetChanged();
			} else if (entity.getEventType() == ColloctionPresenter.ColloctTop_fail) {
				MyToast.toast("" + entity.getData());
			}
		} else {

		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = null;
		switch (v.getId()) {
		case R.id.edit:
			intent = new Intent(getActivity(), ActivityCollectionEdit.class);
			startActivity(intent);
			break;
		case R.id.img_other:
			intent = new Intent(getActivity(), ActivityCustomerService.class);
			startActivity(intent);
			break;
		case R.id.key_word:
			intent = new Intent(getActivity(), ActivityCollectionSeaech.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	// 收缩
	private void collapse() {
		// TODO Auto-generated method stub
		if (cateTypeModels.size() > 8) {
			gridAdapter = new CollectionGridAdapter(getActivity(),
					cateTypeModels, 8);
		} else {
			gridAdapter = new CollectionGridAdapter(getActivity(),
					cateTypeModels, cateTypeModels.size());
		}

		type_grid.setAdapter(gridAdapter);
		mIsShrink = true;
		load_more_img.setImageResource(R.drawable.collect_up);
		gridAdapter.notifyDataSetChanged();
	}

	// 展开
	private void expand() {
		// TODO Auto-generated method stub
		gridAdapter = new CollectionGridAdapter(getActivity(), cateTypeModels,
				cateTypeModels.size());
		// mlist = mList;
		type_grid.setAdapter(gridAdapter);
		mIsShrink = false;
		load_more_img.setImageResource(R.drawable.collect_down);
		gridAdapter.notifyDataSetChanged();
	}

	public void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}

	protected void setListViewHeightBasedOnChildren(GridView gridview) {
		if (gridview == null)
			return;
		ListAdapter listAdapter = gridview.getAdapter();
		if (listAdapter == null)
			return;
		int totalHeight = 0;
		int count = (int) Math.ceil(listAdapter.getCount() / 4.0);
		View itemView = listAdapter.getView(0, null, gridview);
		itemView.measure(0, 0);
		totalHeight = itemView.getMeasuredHeight();
		ViewGroup.LayoutParams params = gridview.getLayoutParams();
		params.height = (dpTopx(10) + totalHeight) * count;
		gridview.setLayoutParams(params);
	}

	private int dpTopx(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		type = "clean";
		pagesize = 1;
		colloctionPresenter.FenYeQuery(uid, "10", pagesize + "", "", "");
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		type = "load";
		pagesize++;
		colloctionPresenter.FenYeQuery(uid, "10", pagesize + "", "", "");
	}

	void stop() {
		goods_list.stopLoadMore();
		goods_list.stopRefresh();
	}
}
